package com.rightsidetech.system.service.impl;


import com.alibaba.dubbo.common.utils.StringUtils;
import com.rightsidetech.system.dtos.request.SysResourceSetGradeReq;
import com.rightsidetech.system.dtos.request.SysResourceUpdateReq;
import com.rightsidetech.system.entity.SysResource;
import com.rightsidetech.system.entity.SysRoleAccount;
import com.rightsidetech.system.service.SysResourceService;
import com.rightsidetech.system.mapper.SysResourceMapper;
import com.rightsidetech.system.mapper.SysRoleAccountMapper;
import com.rightsidetech.system.mapper.SysRoleResourceMapper;
import com.rightsidetech.commom.base.ResponseData;
import com.rightsidetech.commom.enums.CodeIdEnum;
import com.rightsidetech.commom.utils.BeanValidator;
import com.rightsidetech.commom.utils.StringUtil;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.validation.ConstraintViolation;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service("sysResourceServiceImpl")
public class SysResourceServiceImpl implements SysResourceService {

    @Resource
    private SysResourceMapper sysResourceMapper;
    @Resource
    private SysRoleAccountMapper sysRoleAccountMapper;
    @Resource
    private SysRoleResourceMapper sysRoleResourceMapper;

    /**
     * 批量添加资源菜单
     *
     * @param sysAddResourcesModelList
     * @return
     */
    @Override
    public ResponseData saveAddResources(List<SysResourceUpdateReq> sysAddResourcesModelList) {
        //校验参数
        for (SysResourceUpdateReq req:sysAddResourcesModelList) {
            ConstraintViolation validate = BeanValidator.validate(req);
            if (validate != null) {
                return new ResponseData(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
            }
            //新增判重
            if(StringUtil.isNullorEmpty(req.getId())){
                //
            }else{
                //修改判重
                SysResource sysResource2 = sysResourceMapper.selectByPrimaryKey((req.getId()));
                if (StringUtil.isNullorEmpty(sysResource2)){
                    return ResponseData.fail("存在未找到的记录");
                }
            }

            //判断是否存在重复的记录, name、path、url不能为空
            if(!StringUtil.isNullorEmpty(req.getName()) && !StringUtil.isNullorEmpty(req.getPath()) && !StringUtil.isNullorEmpty(req.getUrl())){
                SysResource sysResource = sysResourceMapper.selectByNameAndPathAndUrl(req.getName(),req.getPath(),req.getUrl());
                if(null != sysResource){
                    if(!StringUtil.isNullorEmpty(req.getId()) && req.getId() > 0){
                        if(!sysResource.getId().equals(req.getId())){
                            return ResponseData.fail("菜单已存在");
                        }
                    }else{
                        return ResponseData.fail("菜单已存在");
                    }
                }

            }


        }
        List<SysResourceUpdateReq> sysAdds = new ArrayList<>();
        List<SysResourceUpdateReq> sysUpdates = new ArrayList<>();
        for (SysResourceUpdateReq sysModel : sysAddResourcesModelList) {
            if (StringUtil.isNullorEmpty(sysModel.getId())) {
                if (StringUtil.isNullorEmpty(sysModel.getIsBlank())) {
                    sysModel.setIsBlank(0);
                }
                if (StringUtil.isNullorEmpty(sysModel.getIsPublic())) {
                    sysModel.setIsPublic(1);
                }
                if (StringUtil.isNullorEmpty(sysModel.getResourceOrder())) {
                    sysModel.setResourceOrder(10);
                }
                if (StringUtil.isNullorEmpty(sysModel.getRootId())) {
                    sysModel.setRootId(3);
                }
                if (StringUtil.isNullorEmpty(sysModel.getParentId())) {
                    ResponseData responseData = new ResponseData();
                    responseData.setCodeId(CodeIdEnum.FAILED.getValue());
                    responseData.setCodeDes("参数错误");
                    return responseData;
                }
                sysAdds.add(sysModel);
            } else {
                sysUpdates.add(sysModel);
            }
        }
        //批量添加
        if (sysAdds.size() > 0) {
            sysResourceMapper.insertResourceList(sysAdds, new Date());
        }
        //批量修改
        if (sysUpdates.size() > 0) {
            for (SysResourceUpdateReq sysUpdate : sysUpdates) {
                SysResource sysResource = sysResourceMapper.selectByPrimaryKey((sysUpdate.getId()));
                if (StringUtil.isNullorEmpty(sysResource)){
                    return ResponseData.fail("未找到此id记录");
                }
                sysResource.setUpdatedAt(new Date());
                sysResource.setName(sysUpdate.getName());
                sysResource.setPath(sysUpdate.getPath());
                sysResource.setUrl(sysUpdate.getUrl());
                sysResource.setIcon(sysUpdate.getIcon());
                if (!StringUtil.isNullorEmpty(sysUpdate.getRootId())) {
                    sysResource.setRootId(sysUpdate.getRootId());
                }

                if (!StringUtil.isNullorEmpty(sysUpdate.getResourceOrder())) {
                    sysResource.setResourceOrder(sysUpdate.getResourceOrder());
                }
                if (!StringUtil.isNullorEmpty(sysUpdate.getIsBlank())) {
                    sysResource.setIsBlank(sysUpdate.getIsBlank().byteValue());
                }
                if (!StringUtil.isNullorEmpty(sysUpdate.getIsPublic())) {
                    sysResource.setIsPublic(sysUpdate.getIsPublic().byteValue());
                }
                if (!StringUtil.isNullorEmpty(sysUpdate.getParentId())) {
                    sysResource.setParentId(sysUpdate.getParentId());
                }

                sysResourceMapper.updateByPrimaryKeySelective(sysResource);
            }
        }
        return ResponseData.success();

    }

    @Override
    public ResponseData delList(List<Long> list) {
        Integer i = 0;
        List<Long> allIds = sysResourceMapper.selectAllId();
        List<Long> delIds = list.stream().filter(allIds::contains).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(delIds)) {
            for (Long delId : delIds) {
//                int count = sysRoleResourceMapper.findByResourceId(delId);
                //对应角色未删除无法删除关联菜单
//                if (count < 1){
                    sysResourceMapper.updateIsDel(delId);
                    //设置子级菜单跟父级菜单同步删除
                    List<SysResource> chileList = sysResourceMapper.selectByParentId(delId);
                    if (null != chileList && chileList.size() > 0) {
                        delChildResource(chileList);
                    }
//                }else {
//                    i++;
//                }
            }
        } else {
            return ResponseData.fail("资源不存在或已被删除");
        }
//        if (i>0){
//            return ResponseData.fail(i+"个菜单未删除成功，对应角色未删除无法删除关联菜单");
//        }
        return ResponseData.success();
    }

    private void delChildResource(List<SysResource> list) {
        for (SysResource sysResource : list) {
            if (sysResource.getIsDeleted() == (byte) 0) {
                sysResourceMapper.updateIsDel(sysResource.getId());
                //设置子级菜单跟父级菜单同步
                List<SysResource> chileList = sysResourceMapper.selectByParentId(sysResource.getId());
                if (null != chileList && chileList.size() > 0) {
                    delChildResource(chileList);
                }
            }
        }
    }

    @Override
    public ResponseData findAllList(Long parentId) {
        List<SysResource> list = sysResourceMapper.selectByParentId(parentId);
        return ResponseData.success(list);
    }

    @Override
    public ResponseData getAllSysResource(Long loginInfoId) throws Exception {
        SysRoleAccount sysRoleAccount = sysRoleAccountMapper.selectByloginInfoId(loginInfoId);

        List<SysResource> list = sysResourceMapper.selectRoleResourceList(sysRoleAccount.getRoleId());

        return ResponseData.success(list);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseData setGreade(List<SysResourceSetGradeReq> list) throws Exception {
        //判断记录是否都存在
        for (SysResourceSetGradeReq req:list) {
            SysResource sysResource = sysResourceMapper.selectByPrimaryKey(req.getId());
            if(null == sysResource){
                return ResponseData.fail("菜单记录不存在");
            }
            if(req.getParentId() != 0){
                sysResource = sysResourceMapper.selectByPrimaryKey(req.getParentId());
                if(null == sysResource){
                    return ResponseData.fail("父级菜单记录不存在");
                }
            }

        }
        //进行修改
        int count = 0;
        for (SysResourceSetGradeReq req:list) {
            SysResource sysResource = new SysResource();
            sysResource.setId(req.getId());
            sysResource.setParentId(req.getParentId());
            sysResource.setUpdatedAt(new Date());
            int number = sysResourceMapper.updateByPrimaryKeySelective(sysResource);
            count += number;
        }
        if(count <= 0){
            return ResponseData.fail("修改失败");
        }
        return ResponseData.success();
    }
}
